import json
import importlib
import os
import traceback
import sys

# Add custom directory to sys.path
sys.path.append(os.path.abspath(os.path.join('..', 'gl0906_common')))
sys.path.append(os.path.abspath(os.path.join('..', 'elftool')))
sys.path.append(os.path.abspath(os.path.join('..', 'hexfiletool')))

from gl0906_logger import gl0906_logger, redirect_output_to_log
from elf_map_a2l import gl0906_a2l_parse
from hexfileshandle import dcheck_and_parse_blocks, dmerge_hex_data, dremove_hex_blocks
from gl0906_command import gl0906_git, run_command

def get_script_dir():
    if getattr(sys, 'frozen', False):
        # If pyinstaller(exe)
        return os.path.dirname(sys.executable)
    else:
        # If py
        return os.path.dirname(os.path.abspath(__file__))

# switch work dir
script_dir = get_script_dir()
os.chdir(script_dir)
print(f"{script_dir}")

def load_config(config_file='config.json'):
    with open(config_file, 'r') as f:
        return json.load(f)

def rename_file_keep_extension(file_path, new_name):
    directory, original_file_name = os.path.split(file_path)
    _, file_extension = os.path.splitext(original_file_name)
    new_file_name = new_name + file_extension
    new_file_path = os.path.join(directory, new_file_name)
    os.rename(file_path, new_file_path)
    return new_file_path

def bsw_release(config):
    release_path = config['release_path']
    release_name = '_'.join(config['name_rules'])
    for file in config['files']:
        new_file = rename_file_keep_extension(file, release_name)
        print(f"rename: {file} --> {new_file}")
        run_command(f"mv {new_file} {release_path}")
        print(f"mv: {new_file} --> {release_path}")
    
    if True == config['git']['enable']:
        print("Git operations...")
        bat_path = os.path.join(script_dir, 'git_push.bat')
        if config['git']['commit'] is None:
            # gl0906_git.git_commit(f"[Release]: {release_name}")
            commit_message = f"[Release]: {release_name}"
        else:
            # gl0906_git.git_commit(config['git']['commit'])
            commit_message = f"{config['git']['commit']}"
        run_command([bat_path, commit_message, config['git']['branch']])

        print("Git operations completed successfully.")

def main():
    config = load_config()
    if True == config['logger']['enable']:
        logger = gl0906_logger(log_dir=config['logger']['log_file_path'], max_files=config['logger']['log_file_count'])
        redirect_output_to_log(logger)
        logger.cleanup_logs()

    if True == config['elf_map_a2l']['enable']:
        print("###### Start: map a2l file!")
        gl0906_a2l_parser = gl0906_a2l_parse(config['elf_map_a2l']['a2l_file'], config['elf_map_a2l']['elf_file'])
        sections = gl0906_a2l_parser.parse_a2l()
        updated_sections = gl0906_a2l_parser.update_ecu_address(sections)
        gl0906_a2l_parser.save_updated_a2l(updated_sections, config['elf_map_a2l']['a2l_out_file'], config['elf_map_a2l']['elf_addr_file'])
        print("###### Finish: map a2l file!")
    
    if True == config['hex_file_handle']['enable']:
        print("###### Prepare: copy hex file!")
        print(f"{config['hex_file_handle']['copyhex']} to {config['hex_file_handle']['apphex']}")
        run_command(f"cp {config['hex_file_handle']['copyhex']} {config['hex_file_handle']['apphex']}")
        print("###### Start: merge hex file!")
        dcheck_and_parse_blocks(config['hex_file_handle']['apphex'])
        dcheck_and_parse_blocks(config['hex_file_handle']['a2lhex'])
        src_addr = int(config['hex_file_handle']['a2laddr'], 16)
        src_len = int(config['hex_file_handle']['a2llen'], 16)
        dst_addr = int(config['hex_file_handle']['appaddr'], 16)
        dmerge_hex_data(config['hex_file_handle']['a2lhex'], config['hex_file_handle']['apphex'], src_addr, src_len, dst_addr)
        dremove_hex_blocks(config['hex_file_handle']['apphex'], src_addr)
        print("###### Finish: merge hex file!")

    if True == config['bsw_release']['enable']:
        print("###### Start: release version!")
        bsw_release(config['bsw_release'])
        print("###### Finish: release version!")

if __name__ == "__main__":
    main()
